#include "Logger.h"

#include <pthread.h>

#include <log4cpp/Appender.hh>
#include <log4cpp/Category.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/RollingFileAppender.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/BasicLayout.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>
#include <string>

using namespace log4cpp;

//log4cpp单例模式
namespace l

{

    //静态成员初始化
    pthread_once_t Logger::ms_onceControl = PTHREAD_ONCE_INIT;
    Logger* Logger::ms_instance = Logger::getInstance();

    Logger* Logger::getInstance() {

        pthread_once(&ms_onceControl, initRoutine);

        return ms_instance;
    }

    void Logger::warn(const char* msg) {
        m_category.warn(msg);
    }

    void Logger::error(const char* msg) {
        m_category.error(msg);
    }

    void Logger::debug(const char* msg) {
        m_category.debug(msg);
    }

    void Logger::info(const char* msg) {
        m_category.info(msg);
    }

    Logger::Logger()
        :m_category(Category::getInstance("CloudDisk"))
    {
        //回卷文件输出器
        //new一个输出器
        RollingFileAppender* appender = new RollingFileAppender("rolling", "./log/CloudDisk.log", 1024 * 1024, 3);
        //new一个格式器
        PatternLayout* layout = new PatternLayout();
        //自定义格式器
        layout->setConversionPattern("%c %d [%p] %m%n");
        //输出器绑定格式器
        appender->setLayout(layout);

        //设置优先级(添加过滤器),记录器绑定输出器
        m_category.setPriority(Priority::DEBUG);
        m_category.addAppender(appender);

    }

    Logger::~Logger() {
        Category::shutdown();
    }

    void Logger::destroy() {

        delete ms_instance;
        ms_instance = nullptr;

    }

    void Logger::initRoutine() {
        if (ms_instance == nullptr) {
            ms_instance = new Logger();
            atexit(destroy);
        }

    }

}//end of namespace l